<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import axios from 'axios';
// 添加搜索防抖
import { debounce } from 'lodash-es'
import { getAvailableCoupons, useCoupon } from '@/utils/couponStore'

// 分类接口
interface Category {
  id: number;
  name: string;
  icon: string;
}

// 商品接口
interface Product {
  id: number;
  name: string;
  price: number;
  image: string;
  tag: string;
  description?: string;
}
const router = useRouter();
const value = ref(''); // 搜索框的值

// 搜索相关状态
const showSearchSuggestions = ref(false);
const isSearching = ref(false);
const searchResults = ref<Product[]>([]);

// 合并搜索功能
const searchManager = {
  history: ref<string[]>(JSON.parse(localStorage.getItem('searchHistory') || '[]')),
  results: searchResults,
  isSearching,
  
  debounced: debounce(async (keyword: string) => {
    if (!keyword.trim()) return
    isSearching.value = true
    try {
      await searchManager.perform(keyword)
    } finally {
      isSearching.value = false
    }
  }, 300),
  
  async perform(keyword: string) {
    try {
      const response = await axios.get(`${baseURL}/search`, { params: { keyword } })
      this.results.value = response.data.code === 200 ? response.data.data : this.performLocal(keyword)
    } catch (error) {
      this.results.value = this.performLocal(keyword)
    }
    
    this.addToHistory(keyword)
    if (this.results.value.length === 0) showToast('没有找到相关商品')
  },
  
  performLocal(keyword: string) {
    const allProducts = [...newUserGifts.value, ...hotProducts.value, ...recommendProducts.value]
    return allProducts.filter(product => product.name.toLowerCase().includes(keyword.toLowerCase()))
  },
  
  addToHistory(keyword: string) {
    const history = this.history.value.filter(item => item !== keyword)
    history.unshift(keyword)
    this.history.value = history.slice(0, 10)
    localStorage.setItem('searchHistory', JSON.stringify(this.history.value))
  },
  
  clearHistory() {
    this.history.value = []
    localStorage.setItem('searchHistory', JSON.stringify([]))
  }
}

const onSearch = () => {
  searchManager.debounced(value.value)
}


// 购物车相关状态
interface CartItem {
  id: number;
  name: string;
  price: number;
  image: string;
  quantity: number;
  selected: boolean;
}

const cartItems = ref<CartItem[]>(JSON.parse(localStorage.getItem('cartItems') || '[]'));
const showCart = ref(false);

// 添加优惠券相关状态
interface Coupon {
  id: string;
  name: string;
  amount: number;
  minAmount: number;
  type: "discount" | "cash";
  status: "available" | "used" | "expired";
  expireDate: string;
  description: string;
  source: string;
  createTime: string;
}

const selectedCoupon = ref<Coupon | null>(null)
const availableCoupons = ref<Coupon[]>([])
const showCouponSelector = ref(false)

// 合并购物车计算
const cartCalculations = computed(() => {
  const items = cartItems.value
  const selectedItems = items.filter(item => item.selected)
  
  return {
    totalCount: items.reduce((total, item) => total + item.quantity, 0),
    selectedCount: selectedItems.length,
    selectedPrice: selectedItems.reduce((total, item) => total + item.price * item.quantity, 0),
    finalPrice: (() => {
      let price = selectedItems.reduce((total, item) => total + item.price * item.quantity, 0)
      if (selectedCoupon.value) price = Math.max(0, price - selectedCoupon.value.amount)
      return price
    })()
  }
})

// 保持向后兼容的计算属性
const cartTotalCount = computed(() => cartCalculations.value.totalCount)
const selectedTotalPrice = computed(() => cartCalculations.value.selectedPrice)
const selectedCount = computed(() => cartCalculations.value.selectedCount)
const finalPrice = computed(() => cartCalculations.value.finalPrice)

// 返回我的页面
const goBack = () => {
  router.push('/my');
};

// 更新函数调用
const handleSearch = () => {
  if (!value.value.trim()) return
  showSearchSuggestions.value = false
  searchManager.perform(value.value.trim())
}

const performLocalSearch = (keyword: string) => searchManager.performLocal(keyword)
const addToSearchHistory = (keyword: string) => searchManager.addToHistory(keyword)
const clearSearchHistory = () => searchManager.clearHistory()
const useHistorySearch = (keyword: string) => {
  value.value = keyword
  searchManager.perform(keyword)
}

// 清空搜索结果
const clearSearch = () => {
  value.value = '';
  searchResults.value = [];
  showSearchSuggestions.value = false;
};

// 定义数据结构
const newUserGifts = ref<Product[]>([]);
const categories = ref<Category[]>([]);
const hotProducts = ref<Product[]>([]);
const recommendProducts = ref<Product[]>([]);

// 加载状态
const loading = ref({
  newUserGifts: false,
  categories: false,
  hotProducts: false,
  recommendProducts: false
});

// 错误状态
const error = ref({
  newUserGifts: false,
  categories: false,
  hotProducts: false,
  recommendProducts: false
});

// 后端API基础URL
const baseURL = 'http://localhost:3000/api';

// 获取新人首单礼商品数据
const fetchNewUserGifts = async () => {
  loading.value.newUserGifts = true;
  error.value.newUserGifts = false;
  try {
    const response = await axios.get(`${baseURL}/newUserGifts`);
    if (response.data.code === 200) {
      newUserGifts.value = response.data.data;
    } else {
      throw new Error(response.data.msg);
    }
  } catch (err) {
    console.error('获取新人首单礼失败:', err);
    error.value.newUserGifts = true;
    // 使用本地数据作为备份
    newUserGifts.value = [
      { id: 1, name: "智能手表", price: 209, image: "/手表.jpg", tag: "限时优惠" },
      { id: 2, name: "无线耳机", price: 89, image: "/耳机.jpg", tag: "热卖" },
      { id: 3, name: "护腕", price: 55, image: "/护腕.jpg", tag: "新品" },
      { id: 4, name: "瑜伽垫", price: 30, image: "/瑜伽垫.jpg", tag: "特价" },
    ];
  } finally {
    loading.value.newUserGifts = false;
  }
};

// 获取分类数据
const fetchCategories = async () => {
  loading.value.categories = true;
  error.value.categories = false;
  try {
    const response = await axios.get(`${baseURL}/categories`);
    if (response.data.code === 200) {
      categories.value = response.data.data;
    } else {
      throw new Error(response.data.msg);
    }
  } catch (err) {
    console.error('获取分类失败:', err);
    error.value.categories = true;
    // 使用本地数据作为备份
    categories.value = [
      { id: 1, name: "智能手表", icon: "/手表.jpg" },
      { id: 2, name: "无线耳机", icon: "/耳机.jpg" },
      { id: 3, name: "瑜伽垫", icon: "/瑜伽垫.jpg" },
      { id: 4, name: "运动鞋", icon: "/运动鞋.jpg" },
      { id: 5, name: "健身器材", icon: "/健身器材.jpg" },
    ];
  } finally {
    loading.value.categories = false;
  }
};

// 获取热卖商品数据
const fetchHotProducts = async () => {
  loading.value.hotProducts = true;
  error.value.hotProducts = false;
  try {
    const response = await axios.get(`${baseURL}/hotProducts`);
    if (response.data.code === 200) {
      hotProducts.value = response.data.data;
    } else {
      throw new Error(response.data.msg);
    }
  } catch (err) {
    console.error('获取热卖商品失败:', err);
    error.value.hotProducts = true;
    // 使用本地数据作为备份
    hotProducts.value = [
      {
        id: 1,
        name: "运动紧身裤",
        price: 109,
        image: "/运动紧身裤.jpg",
        tag: "热卖",
      },
      { id: 2, name: "运动T恤", price: 69, image: "/运动T恤.jpg", tag: "新品" },
      { id: 3, name: "跑步机", price: 1709.05, image: "/跑步机.png", tag: "限时" },
      { id: 4, name: "哑铃套装", price: 349.05, image: "/哑铃.jpg", tag: "特价" },
    ];
  } finally {
    loading.value.hotProducts = false;
  }
};

// 获取推荐商品数据
const fetchRecommendProducts = async () => {
  loading.value.recommendProducts = true;
  error.value.recommendProducts = false;
  try {
    const response = await axios.get(`${baseURL}/recommendProducts`);
    if (response.data.code === 200) {
      recommendProducts.value = response.data.data;
    } else {
      throw new Error(response.data.msg);
    }
  } catch (err) {
    console.error('获取推荐商品失败:', err);
    error.value.recommendProducts = true;
    // 使用本地数据作为备份
    recommendProducts.value = [
      {
        id: 1,
        name: "低脂零食大礼包",
        price: 66,
        image: "/零食.jpg",
        tag: "限时",
        description: "营养均衡，助力健身",
      },
      {
        id: 2,
        name: "香薰蜡烛",
        price: 39,
        image: "/香薰蜡烛.jpg",
        tag: "新品",
        description: "瑜伽冥想必备",
      },
      {
        id: 3,
        name: "智能跑步机",
        price: 2099,
        image: "/跑步机.jpg",
        tag: "热卖",
        description: "家用静音可折叠",
      },
    ];
  } finally {
    loading.value.recommendProducts = false;
  }
};

// 处理商品点击
const handleProductClick = (product: Product | number) => {
  // 如果传入的是商品对象，取其id；如果是id，直接使用
  const productId = typeof product === 'object' ? product.id : product;
  router.push(`/product/${productId}`);
};

// 处理分类点击
const handleCategoryClick = (category: Category) => {
  // router.push(`/category/${category.id}`);
};

// 处理加入购物车
const handleAddToCart = (product: any) => {
  const existingItem = cartItems.value.find(item => item.id === product.id);
  
  if (existingItem) {
    existingItem.quantity += 1;
  } else {
    cartItems.value.push({
      id: product.id,
      name: product.name,
      price: product.price,
      image: product.image,
      quantity: 1,
      selected: true
    });
  }
  
  saveCartToStorage();
};

// 更新商品数量
const updateQuantity = (itemId: number, quantity: number) => {
  const item = cartItems.value.find(item => item.id === itemId);
  if (item) {
    if (quantity <= 0) {
      removeFromCart(itemId);
    } else {
      item.quantity = quantity;
      saveCartToStorage();
    }
  }
};

// 从购物车移除商品
const removeFromCart = (itemId: number) => {
  const index = cartItems.value.findIndex(item => item.id === itemId);
  if (index > -1) {
    cartItems.value.splice(index, 1);
    saveCartToStorage();
  }
};

// 切换商品选中状态
const toggleItemSelection = (itemId: number) => {
  const item = cartItems.value.find(item => item.id === itemId);
  if (item) {
    item.selected = !item.selected;
    saveCartToStorage();
  }
};

// 全选/取消全选
const toggleSelectAll = () => {
  const allSelected = cartItems.value.every(item => item.selected);
  cartItems.value.forEach(item => {
    item.selected = !allSelected;
  });
  saveCartToStorage();
};

// 保存购物车到本地存储
const saveCartToStorage = () => {
  localStorage.setItem('cartItems', JSON.stringify(cartItems.value));
};

// 加载可用优惠券
const loadAvailableCoupons = () => {
  const totalAmount = cartCalculations.value.selectedPrice
  availableCoupons.value = getAvailableCoupons(totalAmount)
}

// 选择优惠券
const selectCoupon = (coupon: Coupon) => {
  selectedCoupon.value = coupon
  showCouponSelector.value = false
}

// 清空购物车
const clearCart = () => {
  cartItems.value = [];
  saveCartToStorage();
};

// 结算
const checkout = () => {
  const selectedItems = cartItems.value.filter(item => item.selected);
  if (selectedItems.length === 0) {
    showToast('请选择要结算的商品');
    return;
  }
  
  // 将选中的商品信息和优惠券信息传递给结算页面
  const checkoutData = {
    items: selectedItems,
    totalPrice: cartCalculations.value.selectedPrice,
    totalCount: cartCalculations.value.selectedCount,
    selectedCoupon: selectedCoupon.value // 传递优惠券信息但不使用
  };
  
  // 关闭购物车弹窗
  showCart.value = false;
  
  // 使用localStorage存储数据而不是通过URL参数
  localStorage.setItem('checkoutData', JSON.stringify(checkoutData));
  
  // 跳转到结算页面，不传递复杂数据
  router.push('/checkout');
};

// 显示购物车
const showCartModal = () => {
  showCart.value = true;
  loadAvailableCoupons();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchNewUserGifts();
  fetchCategories();
  fetchHotProducts();
  fetchRecommendProducts();
});
</script>

<template>
  <div class="shop-container">
    <!-- 搜索栏 - 增强版 -->
    <div class="search-bar">
      <div class="back-button" @click="goBack">
        <i class="back-icon">←</i>
      </div>
      <div class="search-wrapper">
        <van-search
          v-model="value"
          placeholder="搜索商品"
          shape="round"
          background="transparent"
          @search="handleSearch"
          @focus="showSearchSuggestions = true"
          @clear="clearSearch"
          show-action
        >
          <template #action>
            <div @click="handleSearch" class="search-action">搜索</div>
          </template>
        </van-search>
      </div>
      <div class="cart-wrapper" @click="showCartModal">
        <van-icon name="cart-o" size="24" class="cart-icon" />
        <van-badge v-if="cartCalculations.totalCount > 0" :content="cartCalculations.totalCount" class="cart-badge" />
      </div>
    </div>

    <!-- 搜索建议和历史 -->
    <div v-if="showSearchSuggestions && !isSearching" class="search-suggestions">
      <div v-if="searchManager.history.value.length > 0" class="search-history">
        <div class="history-header">
          <span>搜索历史</span>
          <van-button type="primary" size="mini" @click="clearSearchHistory">清空</van-button>
        </div>
        <div class="history-tags">
          <van-tag
            v-for="keyword in searchManager.history.value"
            :key="keyword"
            type="default"
            size="medium"
            @click="useHistorySearch(keyword)"
            class="history-tag"
          >
            {{ keyword }}
          </van-tag>
        </div>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searchResults.length > 0" class="search-results">
      <div class="section-header">
        <span class="title">搜索结果 ({{ searchResults.length }})</span>
        <van-button type="primary" size="mini" @click="clearSearch">清空搜索</van-button>
      </div>
      <div class="product-list">
        <van-card
          v-for="product in searchResults"
          :key="product.id"
          :price="product.price"
          :title="product.name"
          :thumb="product.image"
          @click="handleProductClick(product.id)">
          <template #tag>
            <van-tag type="danger">{{ product.tag || '搜索结果' }}</van-tag>
          </template>
          <template #footer>
            <van-button
              size="small"
              type="primary"
              @click.stop="handleAddToCart(product)"
            >加入购物车</van-button>
          </template>
        </van-card>
      </div>
    </div>

    <!-- 原有内容区域 -->
    <div v-if="searchResults.length === 0">
      <!-- 新人首单礼 -->
      <div class="section new-user-gifts">
        <div class="section-header">
          <span class="title">新人首单礼</span>
          <van-tag type="primary" size="medium">NEW</van-tag>
        </div>
        <van-loading v-if="loading.newUserGifts" type="spinner" size="24px" />
        <div v-else class="gift-list">
          <van-card
            v-for="item in newUserGifts"
            :key="item.id"
            :price="item.price"
            :title="item.name"
            :thumb="item.image"
            @click="handleProductClick(item.id)"
          >
            <template #tag>
              <van-tag type="danger">{{ item.tag }}</van-tag>
            </template>
            <template #footer>
              <van-button
                size="small"
                type="primary"
                @click.stop="handleAddToCart(item)"
                >加入购物车</van-button
              >
            </template>
          </van-card>
        </div>
      </div>

      <!-- 分类导航 -->
      <div class="section categories">
        <van-loading v-if="loading.categories" type="spinner" size="24px" />
        <div v-else class="category-grid">
          <div
            v-for="category in categories"
            :key="category.id"
            class="category-item"
            @click="handleCategoryClick(category)"
          >
            <img
              :src="category.icon"
              :alt="category.name"
              class="category-icon"
            />
            <span class="category-name">{{ category.name }}</span>
          </div>
        </div>
      </div>

      <!-- 热卖商品 -->
      <div class="section hot-products">
        <div class="section-header">
          <span class="title">热卖商品</span>
          <span class="more">更多 ></span>
        </div>
        <van-loading v-if="loading.hotProducts" type="spinner" size="24px" />
        <div v-else class="product-list">
          <van-card
            v-for="product in hotProducts"
            :key="product.id"
            :price="product.price"
            :title="product.name"
            :thumb="product.image"
            @click="handleProductClick(product.id)"
          >
            <template #tag>
              <van-tag type="danger">{{ product.tag }}</van-tag>
            </template>
            <template #footer>
              <van-button
                size="small"
                type="primary"
                @click.stop="handleAddToCart(product)"
                >加入购物车</van-button
              >
            </template>
          </van-card>
        </div>
      </div>

      <!-- 推荐商品 -->
      <div class="section recommend-products">
        <div class="section-header">
          <span class="title">为你推荐</span>
        </div>
        <van-loading v-if="loading.recommendProducts" type="spinner" size="24px" />
        <div v-else class="product-list">
          <van-card
            v-for="product in recommendProducts"
            :key="product.id"
            :price="product.price"
            :title="product.name"
            :thumb="product.image"
            :desc="product.description"
            @click="handleProductClick(product.id)"
          >
            <template #tag>
              <van-tag type="danger">{{ product.tag }}</van-tag>
            </template>
            <template #footer>
              <van-button
                size="small"
                type="primary"
                @click.stop="handleAddToCart(product)"
                >加入购物车</van-button
              >
            </template>
          </van-card>
        </div>
      </div>
    </div>

    <!-- 购物车弹窗 -->
    <van-popup v-model:show="showCart" position="bottom" :style="{ height: '70%' }">
      <div class="cart-container">
        <div class="cart-header">
          <span class="cart-title">购物车 ({{ cartCalculations.totalCount }})</span>
          <van-button v-if="cartItems.length > 0" type="danger" size="mini" @click="clearCart">
            清空
          </van-button>
        </div>
        
        <div v-if="cartItems.length === 0" class="empty-cart">
          <van-empty description="购物车是空的" />
        </div>
        
        <div v-else class="cart-content">
          <div class="cart-items">
            <div v-for="item in cartItems" :key="item.id" class="cart-item">
              <van-checkbox 
                :model-value="item.selected" 
                @update:model-value="toggleItemSelection(item.id)"
              />
              <img :src="item.image" :alt="item.name" class="item-image" />
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-price">¥{{ item.price }}</div>
              </div>
              <div class="item-controls">
                <van-stepper 
                  :model-value="item.quantity" 
                  @update:model-value="(val) => updateQuantity(item.id, val)"
                  min="0"
                  max="99"
                />
              </div>
              <van-icon 
                name="delete" 
                class="delete-icon" 
                @click="removeFromCart(item.id)"
              />
            </div>
          </div>
          
          <div class="cart-footer">
            <div class="select-all">
              <van-checkbox 
                :model-value="cartItems.every(item => item.selected)"
                @update:model-value="toggleSelectAll"
              >
                全选
              </van-checkbox>
            </div>
            <div class="total-info">
              <div v-if="selectedCoupon" class="coupon-info">
                <span class="coupon-text">优惠券: -¥{{ selectedCoupon.amount }}</span>
              </div>
              <span class="total-text">合计: ¥{{ cartCalculations.finalPrice.toFixed(2) }}</span>
              <span class="selected-count">(已选{{ cartCalculations.selectedCount }}件)</span>
              <div class="coupon-selector" @click="showCouponSelector = true">
                <span>{{ selectedCoupon ? selectedCoupon.name : '选择优惠券' }}</span>
                <van-icon name="arrow" />
              </div>
            </div>
            <van-button 
              type="primary" 
              size="large" 
              @click="checkout"
              :disabled="cartCalculations.selectedCount === 0"
              class="checkout-btn"
            >
              结算
            </van-button>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 优惠券选择弹窗 -->
    <van-popup v-model:show="showCouponSelector" position="bottom" :style="{ height: '50%' }">
      <div class="coupon-container">
        <div class="coupon-header">
          <span class="coupon-title">选择优惠券</span>
          <van-button type="primary" size="mini" @click="showCouponSelector = false">关闭</van-button>
        </div>
        
        <div v-if="availableCoupons.length === 0" class="empty-coupons">
          <van-empty description="暂无可用优惠券" />
        </div>
        
        <div v-else class="coupon-list">
          <div 
            v-for="coupon in availableCoupons" 
            :key="coupon.id" 
            class="coupon-item"
            :class="{ 'selected': selectedCoupon?.id === coupon.id }"
            @click="selectCoupon(coupon)"
          >
            <div class="coupon-amount">¥{{ coupon.amount }}</div>
            <div class="coupon-info">
              <div class="coupon-name">{{ coupon.name }}</div>
              <div class="coupon-desc">{{ coupon.description }}</div>
              <div class="coupon-expire">有效期至: {{ coupon.expireDate }}</div>
            </div>
            <van-icon v-if="selectedCoupon?.id === coupon.id" name="success" class="selected-icon" />
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 底部占位，防止内容被TabBar遮挡 -->
    <div class="bottom-placeholder"></div>
  </div>
</template>

<style scoped>
.back-button {
  background: none;
  border: none;
  color: white;
  font-size: 1.2rem;
  cursor: pointer;
  padding: 5px 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-style: normal;
  font-weight: bold;
  color: #333;
}

.shop-container {
  padding-bottom: 60px;
  background-color: #f7f8fa;
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background-color: #ffffff;
  position: sticky;
  top: 0;
  z-index: 100;
  justify-content: space-between;
}

.back-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  margin-right: 8px;
  cursor: pointer;
}

.search-wrapper {
  flex: 1;
}

.cart-wrapper {
  display: flex;
  justify-content: flex-end;
  width: 40px;
}

.cart-icon {
  color: #333;
}

.section {
  margin: 12px 0;
  background-color: #ffffff;
  border-radius: 8px;
  padding: 12px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.more {
  color: #999;
  font-size: 14px;
}

/* 商品卡片样式优化 */
.gift-list,
.product-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
  padding: 8px 0;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.category-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-bottom: 4px;
}

.category-name {
  font-size: 12px;
  color: #333;
}

.bottom-placeholder {
  height: 50px;
}

/* 卡片样式覆盖 - 修改布局使价格和图片错开 */
:deep(.van-card) {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 12px 8px;
  display: flex;
  flex-direction: column;
}

:deep(.van-card__header) {
  display: flex;
  flex-direction: column;
}

:deep(.van-card__thumb) {
  width: 100%;
  height: 100px;
  float: none;
  position: relative;
  margin-right: 0;
  margin-bottom: 8px;
  left: 0;
}

:deep(.van-card__content) {
  padding-top: 8px;
  width: 100%;
  float: none;
}

:deep(.van-card__title) {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 4px;
}

/* 价格样式优化 */
:deep(.van-card__price) {
  color: #ff5252;
  font-weight: bold;
  font-size: 18px;
  display: flex;
  align-items: center;
  margin-top: 4px;
}

:deep(.van-card__price-integer) {
  font-size: 18px;
}

:deep(.van-card__price-decimal) {
  font-size: 14px;
}

:deep(.van-card__price-currency) {
  font-size: 14px;
  margin-right: 2px;
}

:deep(.van-card__bottom) {
  margin-top: 8px;
}

:deep(.van-button--primary) {
  background-color: #ff5252;
  border-color: #ff5252;
}

:deep(.van-card__price) {
  color: #ff6b6b;
  font-weight: bold;
}
/* 搜索相关样式 */
.search-action {
  color: #1989fa;
  font-size: 14px;
  padding: 0 8px;
}

.search-suggestions {
  background: white;
  padding: 12px;
  border-bottom: 1px solid #eee;
}

.search-history .history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.history-tag {
  cursor: pointer;
}

.search-results {
  background: white;
  margin: 12px;
  border-radius: 8px;
  padding: 12px;
}

/* 购物车相关样式 */
.cart-wrapper {
  position: relative;
  display: flex;
  justify-content: flex-end;
  width: 40px;
  cursor: pointer;
}

.cart-badge {
  position: absolute;
  top: -8px;
  right: -8px;
}

.cart-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.cart-title {
  font-size: 16px;
  font-weight: bold;
}

.empty-cart {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.cart-items {
  flex: 1;
  overflow-y: auto;
  padding: 0 16px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  margin: 0 12px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 14px;
  margin-bottom: 4px;
}

.item-price {
  color: #ff5252;
  font-weight: bold;
}

.item-controls {
  margin: 0 12px;
}

.delete-icon {
  color: #999;
  font-size: 18px;
  cursor: pointer;
}

.cart-footer {
  display: flex;
  align-items: center;
  padding: 16px;
  border-top: 1px solid #eee;
  background: white;
}

.select-all {
  margin-right: 12px;
}

.total-info {
  flex: 1;
  text-align: right;
}

.total-text {
  font-size: 16px;
  font-weight: bold;
  color: #ff5252;
}

.selected-count {
  font-size: 12px;
  color: #999;
  margin-left: 4px;
}

.checkout-btn {
  margin-left: 12px;
  min-width: 80px;
}

/* 优惠券相关样式 */
.coupon-info {
  font-size: 12px;
  color: #ff5252;
  margin-bottom: 2px;
}

.coupon-selector {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #1989fa;
  cursor: pointer;
  margin-top: 4px;
}

.coupon-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.coupon-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.coupon-title {
  font-size: 16px;
  font-weight: bold;
}

.empty-coupons {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.coupon-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.coupon-item {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 12px;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
}

.coupon-item.selected {
  border-color: #1989fa;
  background: #f0f9ff;
}

.coupon-amount {
  font-size: 24px;
  font-weight: bold;
  color: #ff5252;
  margin-right: 16px;
  min-width: 60px;
}

.coupon-info {
  flex: 1;
}

.coupon-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 4px;
  color: #333;
}

.coupon-desc {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.coupon-expire {
  font-size: 12px;
  color: #999;
}

.selected-icon {
  color: #1989fa;
  font-size: 20px;
}
</style>